<template>
  <div>
    <el-form style="display: flex !important; flex-wrap: wrap">
      <el-form-item label="城市">
          <el-select v-model="deptNameLossreport" placeholder="请选择城市" size="small" style="width: 120px;" @change="handleCityLossreport" ref="deptNameRef" @keydown.native="selectBlur($event)">
            <el-option v-for="(house,citykey) in cityList" :key="citykey" :label="house.deptName" :value="{value:house.id,label:house.deptName}"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="后台单号">
        <el-input
          v-model="orderNumber"
          placeholder="请输入订单号"
          style="width: 160px"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="创建工单时间">
        <el-date-picker
          v-model="Launchdate"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm"
          format="yyyy-MM-dd HH:mm"
          :clearable="true"
          align="right"
          size="small"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="申诉原因">
        <el-select
          v-model="applicationValue"
          placeholder="请选择"
          style="width: 320px"
          clearable
        >
          <el-option
            v-for="item in application"
            :key="item.dictValue"
            :label="item.label"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
        <!-- <el-input v-model="applicationValue"  placeholder="请选择" style="width: 180px" clearable></el-input> -->
      </el-form-item>
      <el-form-item label="处理状态">
        <el-select
          v-model="ProcessingStatusValue"
          placeholder="请选择"
          style="width: 120px"
          clearable
        >
          <el-option
            v-for="item in ProcessingStatus"
            :key="item.dictValue"
            :label="item.label"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          plain
          @click="handleFilterproblem('One')"
          size="small"
          icon="el-icon-search"
        >查询
        </el-button
        >
      </el-form-item>
    </el-form>
    <el-table :data="tableData" border style="width: 100%" header-row-class-name="header-row-class-name"
              cell-class-name="table-cell-class-name">
      <el-table-column prop="orderNo" label="后台单号" align="center"></el-table-column>
      <el-table-column prop="city" label="城市" align="center"  width="200"></el-table-column>
      <el-table-column prop="warehousingTime" label="入库时间" align="center" width="200"></el-table-column>
      <el-table-column label="配送时间" align="center" width="220">
        <template slot-scope="scope">
          {{ changeTime(scope.row.deliveryStartTime, scope.row.deliveryEndTime) }}
          <!-- prop="deliveryEndTime"  -->
        </template>
      </el-table-column>
      <el-table-column prop="receivedTime" label="实际签收时间" align="center" width="200"></el-table-column>
      <el-table-column prop="receiverAddress" label="收货地址" align="center" width="250"></el-table-column>
      <!-- <el-table-column prop="explain" label="申诉类型"  align="center">
        <template slot-scope="scope">
          {{changeReasons(scope.row.relationType)}}
        </template>
      </el-table-column> -->
      <el-table-column prop="reason" label="申诉原因" align="center" width="150"></el-table-column>
      <el-table-column prop="explain" label="申诉说明" align="center" width="200"></el-table-column>
      <el-table-column prop="appealTime" label="申诉时间" align="center" width="200"></el-table-column>
      <el-table-column label="证明材料" align="center" width="300">
        <template slot-scope="scope">
          <div class="photoWallboard">
            <img :src="item" v-for="(item,index) in scope.row.materials.split(',')" :key="index"
                 class="showExplain" @click="handBigPhoto(item)">
            <!-- <img :src="scope.row.materials"  class="showExplain" @click="handBigPhoto(scope.row.materials)"/> -->
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="checkMan" label="审核人" align="center" width="200"></el-table-column>
      <el-table-column prop="auditText" label="处理结果" align="center" width="120"></el-table-column>
      <el-table-column label="处理状态" align="center">
        <template slot-scope="scope">
          <div :class="scope.row.auditState ==1?'red':scope.row.auditState ==2 ? 'green':'blure' ">
            {{ changeName(scope.row.auditState) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini" plain style="margin-left: 0;padding: 7px;margin-bottom: 2px;margin-right: 2px;"
            @click="handSubmitToast(scope.row)">查看
          </el-button>
          <el-button
            v-show="scope.row.isEnd != 1"
            size="mini" plain style="margin-left: 0;padding: 7px;margin-bottom: 2px;margin-right: 2px;"
            @click="endSubmit(scope.row)">结案
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="工单申诉"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose">
      <div>
        <el-radio v-model="radio" label="2">同意申诉</el-radio>
        <el-radio v-model="radio" label="3">拒绝申诉</el-radio>
      </div>

      <h3 style="margin-top: 50px">处理结果:</h3>
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model.trim="textarea"
        maxlength="250"
        show-word-limit
      >
      </el-input>
      <div class="type-button">
        <el-button type="success" v-show="isEnd != 1" size="small" @click="subitworkComplaint(activeValue)">提交
        </el-button>
        <el-button type="primary" v-show="isEnd != 1" size="small" @click="handleClose">关闭</el-button>
        <el-button
          type="info"
          size="small"
          plain
          @click="handlerLogdamage(activeValue)"
        >日志
        </el-button>
      </div>
    </el-dialog>
    <div class="block" v-show="totals">
      <el-pagination
        style="margin-top: 20px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size=size
        layout="total, sizes, prev, pager, next"
        :total='totals'>
      </el-pagination>
    </div>

    <el-dialog
      :visible.sync="isImgShow"
      width="50%"
      :before-close="handImgShow">
      <img :src="src" style="width: 100%"/>
    </el-dialog>


    <el-dialog title="日志" :visible.sync="LogFormVisible" width="width:400px">
      <div class="radio">显示方式：
        <el-radio-group v-model="reverse">
          <el-radio :label="true">倒序</el-radio>
          <el-radio :label="false">正序</el-radio>
        </el-radio-group>
      </div>
      <el-timeline :reverse="reverse">
        <el-timeline-item
          v-for="(activity, index) in LogList"
          :key="index"
          :icon="activity.icon"
          :type="activity.type"
          :color="activity.color"
          :size="activity.size"
          :timestamp="activity.createtime"
        >
          <h5>{{ activity.operator }}</h5>
          <h4 v-html="activity.auditText">{{ activity.auditText }}</h4>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import {
  relationtype,
  workTimeoutListPage,
  workTimeoutlaintAudit,
  workTimeoutlaintAuditEnd,
  deptdepts,
  listAuditLog
} from "@/api/workorder";

export default {
  data() {
    return {
      deptName: "",
      deptNameLossreport: "",
      cityList: [],
      LogList: [], //日志表
      reverse: false,
      LogFormVisible: false,
      isEnd: 0,
      src: '',   // 点击图片地址
      isImgShow: false,  // 图片弹出框
      activeValue: {}, //点击的对象
      radio: '2',   //单选项
      textarea: '',   //输入框内容
      dialogVisible: false, //弹框显示
      orderNumber: "", //后台单号
      Launchdate: [
        this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00")
          .toString(),
        this.dayjs(new Date())
          .format("YYYY-MM-DD 23:59")
          .toString()
      ], // 创建工单时间
      application: [{
        label: '城市超负荷(须上传本小时超3单的APP订单截图)',
        dictValue: 1
      }, {
        label: '生产超时(须上传生产群聊记录截图)',
        dictValue: 2
      },
        {
          label: '客户下错时间/改时间(须上传天使沟通群报备截图)',
          dictValue: 3
        },
        {
          label: '客户定位错误(须上传天使沟通群报备截图)',
          dictValue: 4
        },
        {
          label: '中转不及时(须上传城市运力群聊记录截图)',
          dictValue: 5
        },
        {
          label: '其他(须上传证明图片)',
          dictValue: 6
        },
      ],    // 申请原因列表
      ProcessingStatus: [],  // 处理状态列表
      applicationValue: "", // 申诉原因
      ProcessingStatusValue: "", //处理状态
      currentPage: 1,  //当前页数
      size: 10, // 查找页数
      totals: 0,   //总页数
      tableData: [], // 列表数组
      dataObject: {}, // 列表对象
      remindersform: {
          deptId: ''
      },
      Lossreportform : {
          deptId: ''
      },
    };
  },
  watch: {
    'radio'(value) {
      this.dataObject['radio'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'textarea'(value) {
      this.dataObject['textarea'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'orderNumber'(value) {
      this.dataObject['orderNumber'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'Launchdate'(value) {
      this.dataObject['Launchdate'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'applicationValue'(value) {
      this.dataObject['applicationValue'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'ProcessingStatusValue'(value) {
      this.dataObject['ProcessingStatusValue'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'tableData'(value) {
      this.dataObject['tableData'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'totals'(value) {
      this.dataObject['totals'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'currentPage'(value) {
      this.dataObject['currentPage'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    },
    'size'(value) {
      this.dataObject['size'] = value
      this.$store.state.overtimeRepresentations = this.dataObject
    }
  },
   
  methods: {
      // 选择城市
    handleCityLossreport (data) {
      if (data) {
        this.deptNameLossreport = data.label
        this.Lossreportform.deptId = data.value
        if(data.label == '全国' && data.value == 0) this.Lossreportform.deptId = 1
      } else {
        this.Lossreportform.deptId = JSON.parse(
          window.localStorage.getItem("saber-areaId")
        ).content
        this.deptNameLossreport = JSON.parse(
          window.localStorage.getItem("saber-areaname")
        ).content
      }
    },
    // 选择框回车失焦
    selectBlur (e) {
      if (e.keyCode == 13) e.returnValue = false
    },  
    // 根据城市查询
    getCity () {
        deptdepts("").then(res => {
            res.data.data.unshift({
                id: 0,
                deptName: "全国"
            })
            this.deptName = res.data.data[0].deptName
            this.remindersform.deptId = res.data.data[0].id
            this.cityList = res.data.data
        })
    }, 
    handlerLogdamage(item) {  // 投诉工单审批日志
      this.LogFormVisible = true;
      listAuditLog({
        applyId: item.id,
        type: 9
      }).then(response => {
        this.LogList = response.data.data;
      });
    },
    // bigphoto
    handImgShow() {
      this.isImgShow = false
    },
    handBigPhoto(src) {
      this.src = src
      this.isImgShow = true
    },
    // 处理申诉原因
    // changeReasons(str){
    //   let  changeReasonsStr = ''
    //   this.application.map( (item,index)=>{
    //     if(item.dictKey == str){
    //       changeReasonsStr = item.dictValue
    //     }
    //   })
    //   return changeReasonsStr
    // },
    changeTime(start, end) {
      let arr = end.split(' ')[1].split(':')
      arr.pop()
      let startArray = start.split(':')
      startArray.pop()
      let str = `${startArray.join(':')}~${arr.join(':')}`
      return str
    },
    changePhotoList(item) {
      if (!item) {
        return ''
      } else {
        let arr = []
        item.split('"').map((item, index) => {
          if (index % 2 == 1) {
            arr.push(item)
          }
        })
        return arr
      }
    },
    subitworkComplaint(value) {
      if (!this.textarea) {
        this.$message({
          message: '请输入处理结果',
          type: 'error'
        });
        return
      } else {
        let obj = {}
        obj['id'] = value.id
        obj['auditState'] = Number(this.radio)
        obj['auditText'] = this.textarea
        workTimeoutlaintAudit(obj).then(res => {
          if (res.data.code == 200) {
            this.handleClose()
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.handleFilterproblem()
          }
        })
      }
    },
    endSubmit(row) {
      this.$confirm('是否确认结案，结案后不可继续修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let obj = {}
        obj['id'] = row.id
        workTimeoutlaintAuditEnd(obj).then(res => {
          if (res.data.code == 200) {
            this.handleClose()
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.handleFilterproblem()
          }
        })
      });
    },
    changeName(value) {
      if (value == 1) {
        return '待处理'
      } else if (value == 2) {
        return '申诉成功'
      } else {
        return '申诉失败'
      }
    },
    // 提交摁钮
    handleFilterproblem(str) {
      let isStart = true
      if (this.Launchdate) {
        var time1 = Date.parse(this.dayjs(this.Launchdate[0])
          .format("YYYY-MM-DD HH:mm:00")
          .toString());
        var time2 = Date.parse(this.dayjs(this.Launchdate[1])
          .format("YYYY-MM-DD HH:mm:59")
          .toString());
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount > 31) {
          isStart = false
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        }
      }
      if (!isStart) {
        return
      } else {
        let obj = {}
        obj['size'] = this.size,
          str ? obj['page'] = 1 : obj['page'] = this.currentPage
        str ? this.currentPage = 1 : this.currentPage = this.currentPage
        this.orderNumber ? obj['orderNo'] = this.orderNumber : ''
        if (this.applicationValue) {
          this.application.map((item) => {
            if (this.applicationValue == item.dictValue) {
              obj['reason'] = item.label
            }
          })
        }
        if (this.Launchdate) {  // 当时间为空时
          this.Launchdate[0] ? obj['createTime_st'] = `${this.Launchdate[0]}:00` : ''
          this.Launchdate[1] ? obj['createTime_ed'] = `${this.Launchdate[1]}:59` : ''
        }
        // this.application.map((item,index)=>{
        //   if(item.dictValue == this.applicationValue){
        //     obj['relationType'] = item.dictKey
        //   }
        // })
        this.ProcessingStatus.map((item, index) => {
          if (item.dictValue == this.ProcessingStatusValue) {
            obj['auditState'] = item.dictKey
          }
        })
        obj.deptId = this.Lossreportform.deptId
        workTimeoutListPage(obj).then(res => {
          this.tableData = res.data.data.rows     // 获取列表
          this.totals = res.data.data.total
        })
      }
    },
    handleSizeChange(val) {
      this.size = val
      this.handleFilterproblem('One')
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.handleFilterproblem()
    },
    handSubmitToast(value) {
      this.isEnd = value.isEnd
      this.activeValue = value
      this.dialogVisible = true
      this.textarea = ''
    },
    handleClose() {
      this.dialogVisible = false
    },
    ceshi(e) {
      if (e.keyCode == 13) {
        this.handleFilterproblem()
      }
    }
  },
  created() {
    // relationtype({'code':'work_complaint_relation_type'}).then(res=>{
    //   this.application =res.data.data   // 申诉原因
    // })
    this.handleFilterproblem()
    relationtype({'code': 'work_timeout_audit_state'}).then(res => {
      this.ProcessingStatus = res.data.data   // 处理状态
    })
    // 本地存储
    if (this.$store.state.overtimeRepresentations) {
      let selectData = this.$store.state.overtimeRepresentations
      for (let key in selectData) {
        this.$data[key] = selectData[key]
      }
    }
  },
  mounted() {
      this.getCity()
    window.addEventListener("keydown", this.ceshi)
  },
  beforeDestroy() {
    window.removeEventListener('keydown', this.ceshi)
  }
};
</script>

<style lang='scss' scoped>
.photoWallboard {
  .showExplain {
    width: 20%;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.red {
  color: red
}

.blure {
  color: blue
}

.green {
  color: green
}

.type-button {
  margin-top: 50px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.el-form-item {
  display: flex;
  margin-right: 20px;
}

.table-cell-class-name {
  padding: 0 !important;
  font-size: 12px !important;
}

.header-row-class-name {
  font-size: 12px !important;
}
</style>
